<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="16">
          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('项目信息')" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
              <a-input :placeholder="$t('请输入项目编码/名称')" v-model="queryParam.gameInfo" />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('管理状态')" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
              <a-select v-model="queryParam.state">
                <a-select-option value="">{{ $t('全部') }}</a-select-option>
                <a-select-option value="Y">{{ $t('是') }}</a-select-option>
                <a-select-option value="N">{{ $t('否') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('机号')">
              <a-input :placeholder="$t('请输入机号')" v-model="queryParam.machineNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="8" :md="12" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{ $t('重置') }}</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button v-has="'BisGameController:add'" type="primary" @click="handleAdd" icon="plus">{{$t('新增项目')}}</a-button>
      <a-button type="primary" @click="clickBatchEdit" v-has="'BisGameController:edit'">{{ $t('批量修改') }}</a-button>
    </div>
    <a-row style="border: 1px solid #d9d9d9">
      <a-col :span="3">
        <a-tree
          ref="treeBox"
          :tree-data="sortList"
          :props="defaultProps"
          style="background-color: #fff"
          :defaultSelectedKeys="defaultSelectedKeys"
          @select="treeSelect"
        />
      </a-col>
      <a-col :span="21" style="border-left: 1px solid #d9d9d9">
        <a-row>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            class="j-table-force-nowrap"
            :pagination="ipagination"
            :rowSelection="rowSelection"
            @change="handleTableChange"
          >
            <template slot="deviceNum" slot-scope="text, record">
              <a @click="orderDetail(record)">{{ text }}</a>
            </template>
            <span slot="action" slot-scope="text, record">
              <a @click="handleOpt(record)">{{ $t('运营数据') }}</a
              >&nbsp;&nbsp; <a v-has="'BisGameController:edit'" @click="handleEdit(record)">{{ $t('编辑') }}</a
              >&nbsp;&nbsp;
              <a-popconfirm v-has="'BisGameController:delete'" :title="$t('确定删除吗?')" @confirm="() => handleDelete(record.id)">
                <a>{{ $t('删除') }}</a>
              </a-popconfirm>
            </span>
            <span slot="states" slot-scope="text, record">
              <a-switch v-enable-if="'BisGameController:edit'" v-model="record.states" @change="onChange(record)"></a-switch>
            </span>
          </a-table>
        </a-row>
      </a-col>
    </a-row>
    <game-modal ref="modalForm" @ok="modalFormOk"></game-modal>
    <machine-report-modal ref="reportForm"></machine-report-modal>
    <batch-edit-game-modal ref="modalForm1" @ok="modalFormOk" />
  </a-card>
</template>
<script>
import Vue from 'vue'
import moment from 'moment'
import { getAction, deleteAction, postAction } from '@/api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import GameModal from './modules/GameModal'
import MachineReportModal from '../operationreport/modules/MachineReportModal'
import BatchEditGameModal from './modules/BatchEditGameModal'

export default {
  name: 'MachineSetting',
  components: {
    GameModal,
    MachineReportModal,
    BatchEditGameModal
  },
  data() {
    return {
      description: '娱乐项目管理页面',
      loading: false,
      treeItem: 0,
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      defaultSelectedKeys: [],
      columns: [
        {
          title: this.$t('项目编码'),
          align: 'center',
          dataIndex: 'code',
        },
        {
          title: this.$t('项目名称'),
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: this.$t('项目分类'),
          align: 'center',
          dataIndex: 'typeId_dictText',
        },
        {
          title: this.$t('管理状态'),
          align: 'center',
          dataIndex: 'states',
          scopedSlots: { customRender: 'states' },
        },
        {
          title: this.$t('消费方式'),
          align: 'center',
          dataIndex: 'consumeType_dictText',
        },
        {
          title: this.$t('绑定商品'),
          align: 'center',
          dataIndex: 'outputGoodsId_dictText',
        },
        {
          title: this.$t('机位数量'),
          align: 'center',
          dataIndex: 'deviceNum',
          scopedSlots: { customRender: 'deviceNum' },
        },
        {
          title: this.$t('备注'),
          align: 'center',
          dataIndex: 'comment',
        },
        {
          title: this.$t('操作'),
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      dataSource: [],
      queryParam: {
        gameInfo: '',
        state: '',
        machineNo: '',
        consumeType: '1',
        column: 'createTime',
        order: 'desc',
      },
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total', { total: total })
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onShowSizeChange: (current, pageSize) => this.handleSizeChange(current, pageSize),
      },
      url: {
        list: '/game/bisGame/list',
        delete: '/game/bisGame/delete',
      },
      typeId: '',
      sortList: [],
      indexs: 0,
      stateList: [],
      batchList: [],
      selectedRowKeys: [],
      selectionRows: [],
    }
  },
  created() {
    this.getSortList()
    this.initDictConfig()
  },
  computed: {
    rowSelection() {
      let _this = this
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: (selectedRowKeys, selectionRows) => {
          _this.onSelectChange(selectedRowKeys, selectionRows)
        },
      }
    },
  },
  methods: {
    initDictConfig() {
      initDictOptions('bis_game.consume_type').then((res) => {
        if (res.success) {
          this.stateList = res.result
        }
      })
    },
    treeSelect(data) {
      this.treeItem = data[0]
      this.typeId = data[0];
      this.getList(1)
    },
    getSortList() {
      let that = this
      getAction('/game/bisGameType/rootList', { pageSize: 1000 }).then((res) => {
        if (res.success) {
          let list=res.result.records
          if (list.length > 0) {
            list.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            that.sortList = that.getDataByResult(list)
            that.sortList.unshift({ key: '', id: '', title: that.$t('全部') })
            that.treeItem = that.sortList[0].id
            that.typeId = that.sortList[0].id
            that.defaultSelectedKeys.push(that.sortList[0].key)
            that.getList(1)
          }
        }
      })
    },
    getHasChild(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      query.consumeType = 1
      getAction('/game/bisGameType/childList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.sortList = [...that.sortList]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    handleSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize
    },
    getList(num) {
      let that = this
      let querydata = {}
      querydata = that.queryParam
      that.ipagination.current = num
      querydata.pageNo = that.ipagination.current
      querydata.pageSize = that.ipagination.pageSize
      querydata.typeId = that.typeId
      that.loading = true
      getAction('/game/bisGame/list', querydata)
        .then((res) => {
          if (res.success) {
            res.result.records.forEach((col) => {
              if (col.state == 'Y') {
                col.states = true
              } else {
                col.states = false
              }
            })
            that.dataSource = res.result.records
            if (res.result.total) {
              that.ipagination.total = res.result.total
            } else {
              that.ipagination.total = 0
            }
          }
        })
        .finally(() => {
          that.loading = false
        })
    },
    handleEdit(record) {
      this.$refs.modalForm.edit(record, 2)
      this.$refs.modalForm.title = this.$t('编辑')
    },
    handleAdd() {
      this.$refs.modalForm.add(2)
      this.$refs.modalForm.title = this.$t('新增')
    },
    searchReset() {
      this.indexs = 0
      this.typeId = this.treeItem = this.sortList[0].id
      this.defaultSelectedKeys=[]
      this.defaultSelectedKeys.push(this.sortList[0].key)
      this.queryParam = {
        gameInfo: '',
        state: '',
        machineNo: '',
        consumeType: '1',
        column: 'createTime',
        order: 'desc',
        pageNo: 1,
      }
      this.getList()
    },
    clickBatchEdit() {
      if (this.batchList.length > 0) {
        this.$refs.modalForm1.edit(this.batchList)
      } else {
        this.$message.warning(this.$t('请选择需要批量修改的商品'))
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
      this.batchList = []
      selectionRows.forEach((row) => {
        this.batchList.push(row.id)
      })
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    searchQuery() {
      this.getList(1)
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    onChange(e) {
      e.state = e.states ? 'Y' : 'N'
      postAction('/game/bisGame/edit', { id: e.id, state: e.state }).then((res) => {
        if (res.success) {
          res.result.records.forEach((col) => {
            if (col.state == 'Y') {
              col.states = true
            } else {
              col.states = false
            }
          })
          this.dataSource = res.result.records
        }
      })
    },
    handleDelete(id) {
      let that = this
      if (!that.url.delete) {
        that.$message.error(that.$t('请设置url.delete属性'))
        return
      }
      deleteAction('/game/bisGame/delete', { id: id }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message)
          that.getList(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    modalFormOk() {
      this.getList(this.ipagination.current)
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      this.getList(pagination.current)
    },
    reCalculatePage(count) {
      //总数量-count
      let total = this.ipagination.total - count
      //获取删除后的分页数
      let currentIndex = Math.ceil(total / this.ipagination.pageSize)
      //删除后的分页数<所在当前页
      if (currentIndex < this.ipagination.current) {
        this.ipagination.current = currentIndex
      }
    },
    orderDetail(record) {
      let query = {
        game: record.id,
      }
      this.$router.push({ path: '/terminal/KTDevice', query: query })
    },
    handleOpt(record) {
      let dtl={}
      dtl.createTime_begin = moment(new Date()).format('YYYY-MM-DD 00:00:00')
      dtl.createTime_end = moment(new Date()).format('YYYY-MM-DD 23:59:59')
      dtl.gameId=record.id
      dtl.gameTypeId=record.typeId
      dtl.outputType=record.outputType
      let colSettings = Vue.ls.get('operationreport-GameOperationReport:colsettings')
      let arr = ['memberZlottery','memberAlottery','memberLottery','outputCoin','outputAlottery','outputZlottery', 'outputLottery']
      let columns = []
      let defColumns = [
        {
          title: this.$t('项目名称'),
          align: 'center',
          dataIndex: 'gameId_dictText',
          width: 300,
          customRender: (t, r) => {
            if(!t){
              return this.$t("合计")
            }
            return t
          }
        },
        {
          title: this.$t('支付金额'),
          align: 'center',
          dataIndex: 'payAmount',
          width: 100,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投币'),
          align: 'center',
          dataIndex: 'memberCoin',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投A票'),
          align: 'center',
          dataIndex: 'memberAlottery',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投Z票'),
          align: 'center',
          dataIndex: 'memberZlottery',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投彩票'),
          align: 'center',
          dataIndex: 'memberLottery',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投实币'),
          align: 'center',
          dataIndex: 'physicalCoin',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总投币'),
          align: 'center',
          dataIndex: 'totalCoin',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退彩票'),
          align: 'center',
          dataIndex: 'outputLottery',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退A票'),
          align: 'center',
          dataIndex: 'outputAlottery',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退Z票'),
          align: 'center',
          dataIndex: 'outputZlottery',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退币'),
          align: 'center',
          dataIndex: 'outputCoin',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总退票'),
          align: 'center',
          dataIndex: 'outputValue',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('礼品名称'),
          align: 'center',
          dataIndex: 'outputGoodsId_dictText',
          width: 160,
        },
        {
          title: this.$t('退礼品数'),
          align: 'center',
          dataIndex: 'goodsNumber',
          width: 90,
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投入金额'),
          align: 'center',
          dataIndex: 'inputPrice',
          width: 90,
          customRender: function (t, r) {
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退出金额'),
          align: 'center',
          dataIndex: 'outputPrice',
          width: 100,
          customRender: function (t, r) {
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('毛利润'),
          align: 'center',
          dataIndex: 'profit',
          width: 90,
          customRender: function (t, r) {
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('毛利率'),
          align: 'center',
          dataIndex: 'profitRate',
          width: 120,
          customRender: function (t, r) {
            return t.toFixed(2)+"%"
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('操作'),
          align: 'center',
          dataIndex: 'action',
          width: 140,
          scopedSlots: { customRender: 'action' },
        },
      ]
      if (colSettings == null || colSettings == undefined) {
        defColumns.forEach(function (item, i, array) {
          if(arr.indexOf(item.dataIndex)==-1){
            columns.push(item)
          }
        })
      } else {
        const cols = defColumns.filter((item) => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        columns = cols
      }
      dtl.hideColumns = this.getColumnField(columns,defColumns)
      this.$refs.reportForm.show(dtl, columns)
    },
    getColumnField(list1, list2){
      let arr=[],str=''
      list2.forEach(dk=>{
        let x= list1.findIndex(k=>{
          return dk.dataIndex==k.dataIndex
        })
        if(x==-1){
          arr.push(dk)
        }
      })
      str=arr.map(a=>{return a.dataIndex}).join(',')
      return str
    }
  },
}
</script>
<style scoped>
.col-sort {
  border-bottom: 1px solid #d9d9d9;
  height: 38px;
  line-height: 38px;
  padding-left: 10px;
}
.col-sort-selected {
  border-bottom: 1px solid #d9d9d9;
  height: 38px;
  line-height: 38px;
  padding-left: 10px;
  background-color: #f0f7ff;
}
</style>